package com.dks.util;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;

import org.springframework.web.multipart.MultipartFile;


/**
 * @Author: Ah Nan
 * @Description: AWS上传文件
 * @Date: 15:53 2020/4/22
 * @Modificd By:
 * @Param:
 * @return:
 * @throw: 请描述异常信息
 */
public class AWSFileUploadUtil {

    public URL AWSGetUrl(MultipartFile file) throws IOException{
        URL url = null;
        try {

            // Set the pre-signed URL to expire after one hour.
            java.util.Date expiration = new java.util.Date();
            long expTimeMillis = expiration.getTime();
            expTimeMillis += 1000 * 60 * 60;
            expiration.setTime(expTimeMillis);

            //生成随机文件名
            String localFileName = UUID.randomUUID() + "." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            Date date = new Date();
            SimpleDateFormat formatter_yyyy = new SimpleDateFormat("yyyy");
            SimpleDateFormat formatter_MM = new SimpleDateFormat("MM");
            //在随机名前加上年月
            String s3FileFullPath = formatter_yyyy.format(date) + "/" + formatter_MM.format(date) + "/" + localFileName;

            //获取S3Client对象
            AWSCredentials awsCredentials = new BasicAWSCredentials(Commond.AWS_ACCESS_KEY_ID, Commond.AWS_SECRET_KEY);
            AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCredentials));
            builder.setRegion(Commond.AWS_REGION);
            AmazonS3 s3Client = builder.build();

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(file.getSize());

            // Generate the pre-signed URL.
            System.out.println("Generating pre-signed URL.");
            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(Commond.AWS_BUCKET_NAME, s3FileFullPath)
                    .withMethod(HttpMethod.PUT)
                    .withExpiration(expiration);
            url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

            // Create the connection and use it to upload the new object using the pre-signed URL.
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("PUT");
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write("This text uploaded as an object via presigned URL.");
            out.close();

            // Check the HTTP response code. To complete the upload and make the object available,
            // you must interact with the connection object in some way.
            connection.getResponseCode();
            System.out.println("HTTP response code: " + connection.getResponseCode());

            // Check to make sure that the object was uploaded successfully.
            S3Object object = s3Client.getObject(Commond.AWS_BUCKET_NAME, s3FileFullPath);
            System.out.println("Object " + object.getKey() + " created in bucket " + object.getBucketName());
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process
            // it, so it returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();

        }
        return url;
    }
}
